package com.conversationboard.site;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.conversationboard.config.Configuration;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.keygenerator.KeyGenerator;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.SiteMessage;

public class AutoNumber {

	public static void initialiseAutoNumbers() throws SQLException {

		Connection connection = null;

		try {

			connection = Database.getConnection();

			int maximumThreadId = getMaximum(connection, Queries.GET_MAXIMUM_THREAD_ID);
			int maximumMessageId = getMaximum(connection, Queries.GET_MAXIMUM_MESSAGE_ID);

			KeyGenerator.setThreadKey(maximumThreadId);
			KeyGenerator.setMessageKey(maximumMessageId);

			if ((maximumMessageId == 0) || (maximumThreadId == 0)) {
				System.out
						.println("Welcome to "
								+ Configuration.getInstance().getSiteName()
								+ ". This is a warning message to point out that thread IDs and message IDs have been reset to zero, so we assume this is a new database. If not, something has gone wrong: stop the server and investigate.");
				System.err
						.println("Welcome to "
								+ Configuration.getInstance().getSiteName()
								+ ". This is a warning message to point out that thread IDs and message IDs have been reset to zero, so we assume this is a new database. If not, something has gone wrong: stop the server and investigate.");
				SiteMessage
						.setMessage("Welcome to "
								+ Configuration.getInstance().getSiteName()
								+ ". This is a warning message to point out that thread IDs and message IDs have been reset to zero, so we assume this is a new database. If not, something has gone wrong: stop the server and investigate.");
			}

			Logger.log(new Date(), "Got Autonumber Keys...", null, LogMessageType.SERVER);

		} finally {
			Database.close(connection);
		}

		KeyGenerator.setSuccessfullyInitialised(true);
		SiteMessage.setMessage("");

	}


	private static int getMaximum(Connection connection, String query) throws SQLException {

		int maximum = 0;

		PreparedStatement statement = connection.prepareStatement(query);
		statement.execute();

		ResultSet resultSet = statement.getResultSet();

		while (resultSet.next()) {
			maximum = resultSet.getInt("maximum");
		}

		statement.close();

		return maximum;

	}

}
